package com.gzsxy.esjy.service.netty.decoder;


import com.gzsxy.esjy.common.Assert;
import com.gzsxy.esjy.extraldecoder.IBusinessDecoder;
import com.gzsxy.esjy.handler.BaseHandler;
import com.gzsxy.esjy.request.RequestMessage;
import com.gzsxy.esjy.request.impl.FileHttpServletRequest;
import com.gzsxy.esjy.service.netty.fileServer.configure.ServerStaticProperties;
import com.gzsxy.esjy.service.netty.handler.FileDownloadHandler;
import com.gzsxy.esjy.service.netty.service.FileDownLoadService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;

import java.nio.charset.Charset;

/**
 * 文件下载管理
 * @author zhangxiaolong
 * @date 2022/7/6 9:36
 */
public class FileDownloadDecoder implements IBusinessDecoder<FileHttpServletRequest> {

    private final FileDownLoadService pool;


    public FileDownloadDecoder(FileDownLoadService pool) {

        super();
        this.pool = pool;

    }

    /**
     * 如果该请求为文件上传则为空，否则不为空
     * @param channel
     * @param request
     * @return
     */
    @Override
    public BaseHandler<FileHttpServletRequest> ready(Channel channel, HttpRequest request) {
        String uri = request.uri();
        FileDownloadHandler fileDownloadHandler;
        if (uri.startsWith(ServerStaticProperties.RESOURCES_PREFIX)
                || uri.startsWith(ServerStaticProperties.ABSOLUTE_RESOURCES_PREFIX)) {
            fileDownloadHandler = new FileDownloadHandler(pool);
        }  else {
            return null;
        }

        RequestMessage requestMessage = RequestMessage.createRequestMessage(request);
        //如果请求不为get或者delete 抛异常
        Assert.notTrue(requestMessage.getMethod() == HttpMethod.GET || requestMessage.getMethod() == HttpMethod.DELETE, "mothed not support",
                HttpResponseStatus.METHOD_NOT_ALLOWED.code());
        fileDownloadHandler.setContent(new FileHttpServletRequest(request.protocolVersion(), uri,
                request.headers(), Charset.forName(requestMessage.getCharset()), isKeepAlive(request), requestMessage.getMethod() == HttpMethod.DELETE)
                .setRemoteAddress(channel.remoteAddress().toString()));
        return fileDownloadHandler;
    }

    @Override
    public void decode() {

    }

}
